<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\Model;

class ShopStore extends TimeModel
{

    protected $name = "shop_store";
    protected $deleteTime = 'delete_time';


    public function cate()
    {
        return $this->belongsTo('app\admin\model\ShopCate', 'cate_id', 'id');
    }

    public function goods()
    {
        return $this->hasMany('app\admin\model\ShopGoods', 'store_id', 'id');
    }

    public static function onAfterWrite(Model $model)
    {
        //自动更新redis地理位置
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('dpguo'); //设置密码
        $redis->zRem('stores', $model->id);
        $redis->geoadd('stores', $model->lng, $model->lat, $model->id);
        $redis->set('store_' . $model->id, $model->toJson());
        //如果店铺关闭需要删除缓存并注销定位服务
        if (isset($model->status) && $model->status == 0) {
            $redis->zRem('stores', $model->id);
        }
    }


    public static function onAfterDelete(Model $model)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('dpguo'); //设置密码
        //如果店铺删除需要删除缓存并注销定位服务
        $redis->zRem('stores', $model->id);
        $redis->del('store_' . $model->id);
    }

    public static function onAfterRestore(Model $model)
    {
        //恢复数据后自动更新redis地理位置
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('dpguo'); //设置密码
        $redis->geoadd('stores', $model->lng, $model->lat, $model->id);
        $redis->set('store_' . $model->id, $model->toJson());
    }

}